package cn.jiangjiesheng.bootstrap.commons.filter;

import cn.jiangjiesheng.bootstrap.commons.constants.Profiles;
import cn.jiangjiesheng.bootstrap.commons.context.EntContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * Created by dev@jiangjiesheng.cn on 2021/9/26  <br/>
 *
 * @author dev@jiangjiesheng.cn
 */
@WebFilter(urlPatterns = "/shengxingapi")
@Slf4j
public class EntIdInjectFilter extends OncePerRequestFilter {

    private static final String[] REFERENCE_FIELDS = new String[]{"entId", "containerId"};

    @Value("${spring.profiles.active:dev}")
    private String activeProfile;

    @Value("${defaultEntId:}")
    private String entId;

    /**
     * Same contract as for {@code doFilter}, but guaranteed to be
     * just invoked once per request within a single request thread.
     * See {@link #shouldNotFilterAsyncDispatch()} for details.
     * <p>Provides HttpServletRequest and HttpServletResponse arguments instead of the
     * default ServletRequest and ServletResponse ones.
     *
     * @param request
     * @param response
     * @param filterChain
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        if (Profiles.DEV.equals(activeProfile)) {
            filterChain.doFilter(request, response);
        } else {
            EntContext.reset();
            String entId = null;
            for (String referenceField : REFERENCE_FIELDS) {
                if (StringUtils.isBlank(entId)) {
                    entId = request.getHeader(referenceField);
                } else break;
                if (StringUtils.isBlank(entId)) {
                    entId = request.getParameter(referenceField);
                } else break;
                if (StringUtils.isBlank(entId)) {
                    entId = this.entId;
                } else break;
            }
            if (Objects.nonNull(entId)) {
                EntContext.setEntId(entId);
            }
            filterChain.doFilter(request, response);
        }

    }
}
